package com.guaoran.interview.in23.collection.map;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;

/**
 * @author : 孤傲然
 * @description : HashMap 线程不安全
 * @date :2020/8/26 21:54
 */
public class HashMapThreadUnSafeDemo implements Runnable{
    static Map<String,Object> hashMap = new HashMap<>();
    static CountDownLatch countDownLatch = new CountDownLatch(1);
    public static void main(String[] args) {
//                getHashAndIndex();
        for (int i = 0; i < 100; i++) {
            new Thread(new HashMapThreadUnSafeDemo(),"thread_hash_map"+i).start();
        }
        countDownLatch.countDown();
    }

    public static void getHashAndIndex() {
        int n = 16;
        for (int i = 0; i < 100; i++) {
            int hash = hash("object"+i);
            System.out.println("i=" + i + " => hash=" + hash + " => " + "i 二进制=" + Integer.toBinaryString(i) + "=> hash 二进制" + Integer.toBinaryString(hash) + "\t(hash & n)=" + (hash & n) + " \t=== (hash & 2n)=" + ((2 * n) & hash) + "\t === (hash & n-1)=" + ((n - 1) & hash) + " \t=== \t(hash & (2n-1))=" + ((2 * n - 1) & hash));
        }
//        101011001001101000011111011
//                              10000
//        101011001001101000011111011
//                              ==
//                              10000
//        101011001001101000010000000
//        101011001001101000010011111
//
    }

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

    @Override
    public void run() {
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int j = 0; j < 10000; j++) {
            hashMap.put(UUID.randomUUID().toString(),j++);
        }
        System.out.println(Thread.currentThread().getName()+":"+hashMap.size());
    }
}
